﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using USU.MetricsMonitor.PlotDataProvider;
using USU.MetricsMonitor.Common;
using System.Configuration;

namespace USU.MetricsMonitor.WebUI
{

    public partial class Server : Page
    {
        private Plotter.Plotter plotter;
        private PlotDataProvider.PlotDataProvider pdprovider;

        public Server()
        {
            pdprovider = new PlotDataProvider.PlotDataProvider(ConfigurationManager.AppSettings["storageDir"]);
        }

        protected void Page_Load(Object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string[] projects = pdprovider.getProjectsNames();
                foreach (string pname in projects)
                {
                    projectList.Items.Add(new ListItem(pname));
                }
            }
        }

        protected void ProjectSelected(Object sender, EventArgs e)
        {
            try
            {
                Session["projectName"] = projectList.SelectedValue;
                Session["ttl"] = pdprovider.getProjectTimeLife(Session["projectName"].ToString());
                LPeriod.Text = "Начало: " + ((TTLife)Session["ttl"]).beginTime.ToString() + " " +
                    "Конец: " + ((TTLife)Session["ttl"]).endTime.ToString();
            }
            catch (Exception ex)
            {
                LPeriod.Text = ex.Message;
            }
        }

        protected void OnUpdate(Object sender, EventArgs e)
        {
            try
            {
                string[] projects = pdprovider.getProjectsNames();
                for (int i = projectList.Items.Count; i < projects.Length; i++)
                {
                    projectList.Items.Add(new ListItem(projects[i]));
                }
            }
            catch (Exception ex)
            {
                svnMsg.Text = ex.GetBaseException().Message;
            }
        }

        protected void PeriodSelected(Object sender, EventArgs e)
        {
            try
            {
                if (Page.IsValid)
                {
                        MetricsUsersTree.Nodes.Clear();
                        Session["startDate"] = DateTime.Parse(StartDate.Text);
                        Session["endDate"] = DateTime.Parse(EndDate.Text);
                        Session["lm"] = pdprovider.getAvaliableMetrics(Session["projectName"].ToString(), DateTime.Parse(StartDate.Text),
                            DateTime.Parse(EndDate.Text));
                        foreach (Metric m in (List<Metric>)Session["lm"])
                        {
                            TreeNode tn = new TreeNode(m.Name);
                            tn.SelectAction = TreeNodeSelectAction.None;
                            tn.ToolTip = m.Description;
                            if (m.parameters == null)
                                tn.ShowCheckBox = true;
                            else
                            {
                                if (m.parameters.Count > 0)
                                    tn.ShowCheckBox = false;
                                foreach (MetricParams mp in m.parameters)
                                {
                                    TreeNode ch = new TreeNode(mp.Name);
                                    ch.SelectAction = TreeNodeSelectAction.None;
                                    tn.ChildNodes.Add(ch);
                                }
                            }
                            MetricsUsersTree.Nodes.Add(tn);
                        }
                        UpdatePanel3.Update();
                }
            }
            catch
            {
            }
        }

        protected void ServerValidation(object source, ServerValidateEventArgs args)
        {

            try
            {

                DateTime begin = ((TTLife)Session["ttl"]).beginTime;
                DateTime end = ((TTLife)Session["ttl"]).endTime;
                DateTime x,y,z;
                x = z = DateTime.Parse(StartDate.Text);
                y = DateTime.Parse(EndDate.Text); 

                if (x > y)
                {
                    x = y;
                    y = z;
                    StartDate.Text = x.ToString();
                    EndDate.Text = y.ToString();
                }

                if (x < begin)
                {
                    x = begin;
                    StartDate.Text = x.ToString();
                }
                if (y > end)
                {
                    y = end;
                    EndDate.Text = y.ToString();
                }
            }

            catch
            {
                args.IsValid = false;
            }
        }

        protected void MetricsSelected(Object sender, EventArgs e)
        {
            try
            {
                MetricsSelectedLabel.Text = "";
                if (MetricsUsersTree.CheckedNodes.Count > 0)
                {
                    var m = new Metric();
                    m.parameters = new List<MetricParams>();
                    String s = "";
                    foreach (TreeNode tn in MetricsUsersTree.CheckedNodes)
                    {
                        if (tn.Depth == 0)
                        {
                            if (s == "")
                            {
                                m.Name = s = tn.Text;
                            }
                            else
                            {
                                throw new Exception("Выбрано несколько корневых узлов");
                            }
                        }
                        else
                        {
                            if (s == "")
                            {
                                m.Name = s = tn.Parent.Text;
                            }
                            if (s == tn.Parent.Text)
                            {
                                MetricParams mp = new MetricParams();
                                mp.Name = tn.Text;
                                mp.Check = tn.Checked;
                                m.parameters.Add(mp);
                            }
                            else
                            {
                                throw new Exception("Выбраны узлы с разными родителями");
                            }
                        }
                    }
                    plotter = new Plotter.Plotter(pdprovider.getData((string)Session["projectName"], m, (DateTime)Session["startDate"], (DateTime)Session["endDate"]));
                    ZedGraphWeb.Width = int.Parse(HField1.Value);
                    ZedGraphWeb.Height = int.Parse(HField2.Value);       
                    ZedGraphWeb.RenderGraph += plotter.OnRenderGraph;
                    ZedGraphWeb.Visible = true;
                    UpdatePanel4.Update();
                }
                else
                {
                    throw new Exception("Ничего не выбрано");
                }
            }
            catch (Exception ex)
            {
                MetricsSelectedLabel.Text = ex.Message;
            }
        } 
    } 
}